const { ipcMain, BrowserWindow } = require("electron");

const getSource = (url) => {
  if (!url.startsWith("http")) {
    url = "https://" + url;
  }
  return new Promise((res, rej) => {
    const win = new BrowserWindow({
      width: 1280,
      height: 680,
      show: false,
      webPreferences: {
        offscreen: true,
      },
    });

    win.loadURL(url);

    win.webContents.on("did-finish-load", async () => {
      const title = win.getTitle();
      try {
        const image = await win.webContents.capturePage();
        if (image.isEmpty()) {
          res({
            msg,
          });
        } else {
          const img = image.toDataURL();
          res({
            title,
            img,
            url,
          });
        }
      } catch (e) {
        rej(e);
      }
    });
  });
};

ipcMain.handle("on-url-event", async (e, url) => {
  const res = await getSource(url);
  return res;
});
